package com.bs.bszhsq.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.bs.bszhsq.entity.Users;
import com.bs.bszhsq.exception.ServiceException;
import com.bs.bszhsq.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class    JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private IUsersService usersService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
   //如果不是请求方法直接通过
        if (! (handler instanceof HandlerMethod)){
            return true;
        }else {
            HandlerMethod h=(HandlerMethod) handler;
            AuthAccess methodAnnotation = h.getMethodAnnotation(AuthAccess.class);
            if (!ObjectUtils.isEmpty(methodAnnotation)){
                return true;
            }
        }
         if (StrUtil.isBlank(token)){
             throw new ServiceException("500","未登录，登录了再来哦");
         }
        //获取userid
        String userId;
        try {
            userId= JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException e) {
            throw new ServiceException("500","token验证失败，请重新登录");
        }
        //根据token查询数据库
        Users users = usersService.getById(userId);
        if (BeanUtil.isEmpty(users)){
            throw new ServiceException("500","用户不存在请重新登录");
        }
        //进一步验证token,用户密码加签验证
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(users.getPassword())).build();
        try {
            verifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new ServiceException("500","token有误");
        }
        return true;
    }
}
